<!-- 分页器 -->
<template>
	<view class="me-pagination app-flex" v-if="total">
		<view class="flex-item"></view>
		<view class="total">共{{total}}条</view>
		<view class="num" :class="{active:val.num==num}" v-for="(val,i) in numArr" @click="change(val)" :key="i">{{val.num}}</view>
	</view>
</template>

<script>
	export default {
		props:{
			// 总条数
			total: {
				type: Number,
				default: 0
			},
			// 初始页码 (支持.sync)
			num:{
				type: Number,
				default: 1
			}
		},
		data() {
			return {
				pageNum: this.num, // 当前页码
				pageSize: 10, // 一页总数, 默认10
				pagerCount: 11 // 总数超过这个数会折叠(奇数)
			}
		},
		computed: {
			totalPage(){
				return Math.ceil(this.total / this.pageSize)
			},
			offset(){
				return (this.pagerCount-3)/2 // 前面后偏移量
			},
			numArr() {
				let arr = []
				if (this.totalPage <= this.pagerCount) {
					// 非折叠
					for (let i = 0; i < this.totalPage; i++) {
						arr.push({num: i+1})
					}
				} else{
					arr.push({num: 1})
					if (this.pageNum < this.pagerCount - this.offset) {
						// 折叠后面
						for (let i = 1; i < this.pagerCount - 1; i++) {
							arr.push({num: i+1})
						}
						arr.push({num: "···", type:"next"})
					} else if(this.pageNum >= this.totalPage - this.offset - 1){
						// 折叠前面
						arr.push({num: "···", type:"pre"})
						for (let i = this.totalPage - this.pagerCount + 1; i < this.totalPage-1; i++) {
							arr.push({num: i+1})
						}
					}else{
						// 折叠前面和后面
						arr.push({num: "···", type:"pre"})
						let startNo = this.pageNum - this.offset
						for (let i = 0; i < this.pagerCount-2; i++) {
							arr.push({num: startNo+i})
						}
						arr.push({num: "···", type:"next"})
					}
					arr.push({num: this.totalPage})
				}
				return arr
			}
		},
		watch: {
			num(val) {
				this.pageNum = val
			}
		},
		methods:{
			change(val){
				if(this.pageNum != val.num){
					if (val.type == 'pre') {
						this.pageNum -= this.offset+1
					} else if (val.type == 'next') {
						this.pageNum += this.offset+1
					} else {
						this.pageNum = val.num
					}
					this.$emit('update:num', this.pageNum)
					this.$emit('change', this.pageNum)
				}
			}
		}
	}
</script>

<style lang="scss">
	.me-pagination{
		font-size: 12px;
		.total{
			margin-right: 12px;
			color: #666;
		}
		.num{
			width: 20px;
			height: 20px;
			line-height: 20px;
			text-align: center;
			margin: 5px;
			cursor: pointer;
			&.active{
				background-color: $uni-color-primary;
				color: #fff;
			}
		}
	}
	
	.app-flex{display: flex;align-items: center;}
	.app-flex .flex-item{position: relative;flex: 1;min-width: 0;white-space: nowrap;}
</style>
